/*
Automatic clinic tests using a robot arm.
Copyright (C) 2010  CIC-CPC, CHU Gabriel Montpied
All other trademarks, logos and copyrights are the property
of their respective owners.

This file is part of cpc-painbot.

cpc-painbot is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

cpc-painbot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with cpc-painbot.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "commande/bras/caracteres.h"

#include <QDebug>

#include "commande/bras/init.h"
#include "commande/bras/position.h"
#include "commande/bras/lireposition.h"
#include "commande/bras/reponse.h"

namespace commande {
namespace bras {

const QRegExp Caracteres::format("^@\\w\\w(?:,[^,]+)*\\r$");

Caracteres * Caracteres::lire(const QString &chaine)
{
    Caracteres * cmd = 0;
    //format.setMinimal(true);

    //qDebug() << "Caracteres::lire : " << chaine;

    // On s'assure que le format de la commande
    // soit correct.
    if ( format.exactMatch(chaine) ) {
        // On découpe la chaîne suivant le délimiteur de champ (la virgule).
        // Le code sera toujours le premier éléments de cette liste.
        QStringList arguments = chaine.simplified().split(',');

        // Le premier argument = le code. On le retire.
        // Et on enlève le premier caractère (le @).
        QString code = arguments.takeFirst().remove(0, 1);

       // qDebug() << "Caracteres::lire (code ="  << code << ", arguments =" << arguments;

        if ( code == "R0" )
            cmd = new Init;
        else if ( code == "N1" )
            cmd = new LirePosition;
        else if ( code == "n1" )
            cmd = new Position(arguments);
        else if ( code.contains(QRegExp("^[a-z]")) ) {
            // Tout le reste qui commence par une minuscule : une réponse.
            cmd = new Reponse(code, arguments);
        }
    }

    return cmd;
}

Caracteres::Caracteres(const QString & code, const QStringList & args) :
    Commande(code, args)
{
}

QString Caracteres::generer() const
{
    QString cmd = "@";
    cmd.append(code());

    if ( !arguments_.isEmpty() )
        cmd.append(',').append(arguments_.join(","));

    //qDebug() << "Caracteres::generer :" << cmd;

    cmd.append('\r');
    return cmd;
}

} // namespace bras
} // namespace commande
